package com.my.study.producer.service.Impl;

import com.my.study.producer.service.RocketMqSendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class RocketMqSendServiceImpl implements RocketMqSendService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 同步
     *
     * @param topic
     * @param object
     * @return
     */
    @Override
    public SendResult syncSend(String topic, Object object) {
        return rocketMQTemplate.syncSend(topic,object);
    }

    /**
     * 执行失败,执行SendCallback实现类(可自定义逻辑)==异步
     *
     * @param topic
     * @param object
     * @param sendCallback
     */
    @Override
    public void asyncSend(String topic, Object object, SendCallback sendCallback) {
        rocketMQTemplate.asyncSend(topic,object,sendCallback);
    }

    /**
     * 执行失败数据缓存数据库(异步)
     *
     * @param topic
     * @param object
     */
    @Override
    public void     asyncSendHandlerErrorData(String topic, Object object) {
        rocketMQTemplate.asyncSend(topic, object, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送结果:" + sendResult.toString());
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("异步发送失败,数据缓存到数据库" + throwable);
            }
        });
    }

    /**
     * 发送事务消息
     *
     * @param topic
     * @param message
     */
    @Override
    public TransactionSendResult sendMessageInTransaction(String topic, Message message) {
        return rocketMQTemplate.sendMessageInTransaction(topic,message,null);
    }
}
